<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\Controller;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleController extends Controller
{

  //角色列表
  public function index(Request $request)
  {
    $roles = Role::getList($request);
    return $this->success($roles);
  }

  // 角色详情
  public function detail($id)
  {
    $roleInfo = Role::getInfo($id);
    return $this->success($roleInfo);
  }

  // 新增角色
  public function add(Request $request)
  {
    $data = $request->all();
    $rule = [
      'name'     => 'required',
    ];
    $message = [
      'name.required'       => '角色名称不能为空',
    ];
    $validated = $this->validator($data, $rule, $message);
    if (is_bool($validated)) {
      $insertData = [
        'name' => $request->name,
        'status' => $request->status,
        'code' => $request->code,
        'sort' => $request->sort,
        'remark' => $request->remark,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      $result = DB::table('roles')->insert($insertData);
      return $this->success();
    } else {
      return $validated;
    }
  }

  // 修改角色
  public function update(Request $request)
  {
    $roleInfo = DB::table('roles')->where('id', $request->id)->first();
    if ($roleInfo && $roleInfo->id) {
      $updateData = [
        'name' => $request->name ?? $roleInfo->name,
        'status' => $request->status ?? $roleInfo->status,
        'code' => $request->code ?? $roleInfo->code,
        'sort' => $request->sort ?? $roleInfo->sort,
        'remark' => $request->remark ?? $roleInfo->remark,
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      $result = DB::table('roles')->where('id', $request->id)->update($updateData);
      if ($result) {
        return $this->success();
      }
      return $this->failed('修改失败');
    } else {
      return $this->failed('角色不存在');
    }
  }

  // 删除角色
  public function delete($id)
  {
    $result = DB::table('roles')->where('id', $id)->delete();
    if ($result) {
      return $this->success();
    }
    return $this->failed('删除失败');
  }
}
